module Kuztuscms
  class LayoutsController < KuztuscmsController
    before_filter :build_locales_list, :only => [:new, :edit, :create, :update]
    before_filter :build_handlers_list, :only => [:new, :edit, :create, :update]
    before_filter :build_formats_list, :only => [:new, :edit, :create, :update]

    # GET /layouts
    def index
      @layouts = Layout.all
    end

    # GET /layouts/1
    def show
      @layout = Layout.find(params[:id])
    end

    # GET /layouts/new
    def new
      @layout = Layout.new(:format => 'html', :body => Layout.find_by_path('default').body)
    end

    # GET /layouts/1/edit
    def edit
      @layout = Layout.find(params[:id])
    end

    # POST /layouts
    def create
      @layout = Layout.new(params[:layout])
      @layout.partial = false

      if @layout.save
        redirect_to layouts_url, notice: 'Layout was successfully created.'
      else
        render action: "new"
      end
    end

    # PUT /layouts/1
    def update
      @layout = Layout.find(params[:id])
  
      if @layout.update_attributes(params[:layout])
        redirect_to layouts_url, notice: 'Layout was successfully updated.'
      else
        render action: "edit"
      end
    end

    # DELETE /layouts/1
    def destroy
      @layout = Layout.find(params[:id])
      if @layout.path == 'default'
        redirect_to layouts_url, notice: 'You cannot delete default layout'
      else
        @layout.destroy
        redirect_to layouts_url, notice: 'Layout was successfully deleted.'
      end
    end

    private 

      def build_formats_list
        @formats = Mime::SET.symbols.map(&:to_s)
      end

      def build_locales_list
        @locales = I18n.available_locales.map(&:to_s)
      end

      def build_handlers_list
        @handlers = ActionView::Template::Handlers.extensions.map(&:to_s)
      end
  end
end
